package org.sgroup.imenu;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.sgroup.imenu.bo.Category;
import org.sgroup.imenu.bo.Item;
import org.sgroup.imenu.controladapter.ITabsFragment;
import org.sgroup.imenu.controladapter.ITabsAdapter;
import org.sgroup.imenu.controladapter.OrderListAdapter;
import org.sgroup.imenu.controlview.ITabs;
import org.sgroup.imenu.service.IMenuService;
import org.sgroup.imenu.service.IMenuXmlSerialize;
import org.sgroup.imenu.util.CData;

import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class IMenuActivity extends FragmentActivity {

	// private static final String[] TITLES = { "THỨC ĂN", "ĐỒ UỐNG",
	// "RELAX", "OTHER", };

	private ITabs mTabs;
	private ViewPager mViewPager;
	private ArrayList<Item> mOrderListCache;
	private Context mContext;
	private ArrayList<View> mArrView = new ArrayList<View>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_amain);
		// TextView txtReview = (TextView)findViewById(R.id.txtReview);
		// txtReview.setText(TITLES[0]);
		mContext = this;
		mOrderListCache = new ArrayList<Item>();
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mTabs = (ITabs) findViewById(R.id.swipeytabs);
		// Load Data
		IMenuXmlSerialize db = new IMenuXmlSerialize(this);
		db.LoadDatabase();

		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager(), db.getCategories());

		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(0);

		// add event
		CreateEvent();
	}

	private void CreateEvent() {

		TextView btnViewOrder = (TextView) findViewById(R.id.lbOrder);
		btnViewOrder.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mOrderListCache != null) {
					LinearLayout footer = (LinearLayout) findViewById(R.id.footer);
					footer.setVisibility(View.GONE);
					OrderListItemView newView = new OrderListItemView(mContext,
							mOrderListCache);
					ChangeView(newView, false);
				}
			}
		});

	}

	private void ExecuteOrder(Item pItem, int quantity) {

		final HorizontalScrollView hs_order_items = (HorizontalScrollView) findViewById(R.id.hs_order_items);
		int scrollTo = 0;
		LinearLayout layoutView = (LinearLayout) findViewById(R.id.order_items);
		boolean isOrderExisted = false;
		if (mOrderListCache != null) {
			for (Item item : mOrderListCache) {
				if (item.ID == pItem.ID) {
					item.Quantity = item.Quantity + quantity;
					pItem.Quantity = item.Quantity;
					isOrderExisted = true;
					break;
				}
			}
		}

		if (isOrderExisted) {
			for (int i = 0; i < layoutView.getChildCount(); i++) {
				View view = layoutView.getChildAt(i);
				int viewID = view.getId();
				if (pItem.ID == viewID) {
					if (pItem.Quantity > 0) {
						RelativeLayout rl = (RelativeLayout) view;
						Button _button = (Button) rl.getChildAt(1);
						if (_button != null) {

							String _quantity = pItem.Quantity + "";
							if (pItem.Quantity < 10) {
								_quantity = "0" + pItem.Quantity;
							}
							_button.setText(_quantity);
							int COLOR_START = Color.parseColor("#FF0000");
							int COLOR_END = Color.parseColor("#414141");

							ValueAnimator colorAnim = ObjectAnimator.ofInt(
									_button, "textColor", COLOR_START,
									COLOR_END);
							colorAnim.setDuration(2000);
							colorAnim.setEvaluator(new ArgbEvaluator());
							colorAnim.start();
						}
					} else {
						mOrderListCache.remove(pItem);
						layoutView.removeView(view);
					}
					scrollTo = i * view.getWidth();
					break;
				}
			}
			hs_order_items.scrollTo(scrollTo, 0);

		} else {
			// lưu lại danh sách đặt hàng
			pItem.Quantity = pItem.Quantity + quantity;
			mOrderListCache.add(pItem);
			ArrayList<Item> newOrderList = new ArrayList<Item>();
			newOrderList.add(pItem);

			OrderListAdapter orderApdater = new OrderListAdapter(mContext,
					R.layout.order_view, newOrderList);

			ListAdapter listAdapter = orderApdater;
			if (listAdapter != null && listAdapter.getCount() > 0) {
				View vView = listAdapter.getView(0, null, null);
				layoutView.addView(vView);
			}
			hs_order_items.postDelayed(new Runnable() {
				@Override
				public void run() {
					hs_order_items.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
				}
			}, 100);
		}
		UpdateOrderLabel();
	}

	public void AddOrder(Item pItem) {
		ExecuteOrder(pItem, 1);
	}

	public void RemoveOrder(Item pItem) {
		ExecuteOrder(pItem, -1);
	}

	public void UpdateOrderLabel() {
		int totalMin = 0;
		double totalCost = 0;

		if (mOrderListCache != null) {
			for (Item item : mOrderListCache) {
				int item_time = item.Time;
				if (item_time == 0) {
					item_time = 5;
				}
				totalMin += item_time * item.Quantity;
				totalCost += item.Price * item.Quantity;
			}
		}

		String ret = String.format(
				"Your order will be served in %s minutes\nand cost %s",
				totalMin, CData.FormatPrice(totalCost));

		TextView txt = (TextView) findViewById(R.id.lbl_charge);
		if (txt != null) {
			txt.setText(ret);
		}
	}

	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
			ITabsAdapter {
		private List<Category> categories = null;
		private final Context mContext;

		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);

			this.mContext = context;
		}

		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm,
				List<Category> cats) {
			super(fm);

			this.mContext = context;
			this.categories = cats;
		}

		@Override
		public Fragment getItem(int position) {
			return new ITabsFragment(this.categories.get(position).childs,
					this.mContext);
		}

		@Override
		public int getCount() {
			return this.categories.size();
		}

		public TextView getTab(final int position, ITabs root) {
			TextView view = (TextView) LayoutInflater.from(mContext).inflate(
					R.layout.itab_indicator, root, false);
			view.setText(this.categories.get(position).Name.toUpperCase());
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});

			return view;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void ChangeView(View view, boolean isCallByBackButton) {
		LinearLayout layoutView = (LinearLayout) findViewById(R.id.viewMain);
		if (!isCallByBackButton) {
			View currentView = (View) layoutView.getChildAt(0);
			mArrView.add(currentView);
		}
		layoutView.removeAllViews();
		layoutView.addView(view);

		// check footer
		LinearLayout footer = (LinearLayout) findViewById(R.id.footer);
		if (isCallByBackButton && footer.getVisibility() == View.GONE) {
			footer.setVisibility(View.VISIBLE);
		}
		UpdateOrderLabel();
		Button btnSendOrder = (Button) findViewById(R.id.btnSendOrder);
		if (btnSendOrder != null) {
			btnSendOrder.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// custom dialog
					final Dialog dialog = new Dialog(mContext);
					dialog.setContentView(R.layout.order_confirm_dialog);
					dialog.setTitle("Chọn bàn...");

					Button dialogButtonCancel = (Button) dialog
							.findViewById(R.id.btn_order_confirm_cancel);
					// if button is clicked, close the custom dialog
					dialogButtonCancel
							.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									dialog.dismiss();
								}
							});
					Button dialogButtonOK = (Button) dialog
							.findViewById(R.id.btn_order_confirm_ok);
					// if button is clicked, close the custom dialog
					dialogButtonOK.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (mOrderListCache != null
									&& mOrderListCache.size() > 0) {
								String input = "<input user='lbnam' pass='123456' desc='nhanh nhanh' table='1' parent='3' />";
								String items = "<items>";
								for (Item item : mOrderListCache) {
									items += String
											.format("<item id='%s' quantity='%s' desc='%s' discount='%s'/>",
													item.ID, item.Quantity,
													item.Description,
													item.DisCount);
								}
								items += "</items>";
								String inputValue = input + items;
								Log.i(":::::inputValue>>>>:::::", inputValue);
								String msg = "";
								try {
									msg = new IMenuService()
											.confirmOrder(inputValue);
								} catch (NetworkOnMainThreadException e) {
									msg = e.getMessage();
								}

								Log.i(":::::result:::::", msg);
								AlertDialog.Builder alert = new AlertDialog.Builder(
										mContext);
								alert.setTitle("Thông báo");
								alert.setMessage("Đã gọi hàm IMenuService().confirmOrder:: \n"
										+ msg);

								alert.setPositiveButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface pDialog,
													int whichButton) {
												pDialog.cancel();

											}
										});
								AlertDialog alertDialog = alert.create();
								alertDialog.show();
							}
							dialog.dismiss();
						}
					});
					dialog.show();
				}
			});
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mArrView.size() != 0) {
				int lastIndex = mArrView.size() - 1;
				View prevView = mArrView.get(lastIndex);
				ChangeView(prevView, true);
				mArrView.remove(lastIndex);
			} else
				onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
